import pandas
from matplotlib import pyplot as plt
import random
target_dict={}
def check(keys):
    n=0
    for i in target_dict.keys():
        if i==keys:
            return True
        if n==len(target_dict):
            return False
        n+=1

def sum(list, s=0):
    for item in list:
        s+=item[1]
    return s
def random_color():
    color_list=['0','1','2','3','4','5','6','7','8','9',
                'A','B','C','D','E','F']
    color = ''
    for i in range(6):
        color_number = color_list[random.randint(0,15)]
        color += color_number
    color = '#' +color
    return color
def main():
    university_list=pandas.read_csv('testfile.csv')
    university_location=university_list['location'][:120]
    university_location=list(university_location)
    for item in university_location:
        if check(item):
            target_dict[item]+=1
        else:target_dict[item]=1
    target_dict_demo=list(zip(target_dict.keys(),target_dict.values()))
    # target_dict_demo=list(zip(target_dict.values(),target_dict.keys()))
    # print(target_dict_demo)
    list_demo=sorted(target_dict_demo,key=lambda x:x[1],reverse=True)
    # print(list_demo)
    # print(type(target_dict_demo))
    # print(target_dict_demo[0][0])
    # list_demo=[]
    # for item in target_dict_demo:
    #     item=list(item) #tuple转变问题可问老师
    #     list_demo.append(item)
    # # print(list_demo)
    # # # print(target_dict_demo)
    # for i in range(len(list_demo)):
    #     for j in range(len(list_demo)-i-1):
    #         if list_demo[j][0]<list_demo[j+1][0]:
    #             temp=list_demo[j]
    #             list_demo[j]=list_demo[j+1]
    #             list_demo[j+1]=temp
    # print(list_demo)
    # for item in list_demo:
    #     item=tuple(item)
    # print(list_demo)
    # final_dict={}
    # print(final_dict)
    final_list=[]
    for item in list_demo:
        if item[1] == 1:
            break
        final_list.append(item)
    # print(final_list)
    plt.figure(figsize=(12,12))
    labels=[]
    for item in final_list:
        labels.append(item[0])
    sizes=[]
    for item in final_list:
        sizes.append(item[1]/sum(final_list))
    # print(len(final_list))
    colors=[]
    for i in range(len(final_list)):
        colors.append(random_color())
    patches,text1,text2 = plt.pie(sizes,
                          labels=labels,
                          colors=colors,
                          autopct = '%3.1f%%', #数值保留固定小数位
                          shadow = False, #无阴影设置
                          startangle =90, #逆时针起始角度设置
                          pctdistance = 0.7) #数值距圆心半径倍数距离
    #patches饼图的返回值，texts1饼图外label的文本，texts2饼图内部的文本
    # x，y轴刻度设置一致，保证饼图为圆形
    plt.axis('equal')
    plt.legend() # 右上角显示
    plt.savefig('fan_chart.png')
    plt.show()
if __name__ == '__main__':
    main()



